<template>
  <div class="krpano">
    <div id="pano" style="width: 100%; height: 100%" v-if="ifKrpano">
      <noscript>
        <table style="width: 100%; height: 100%">
          <tr style="vertical-align: middle">
            <td>
              <div style="text-align: center">
                ERROR:
                <br />
                <br />Javascript not activated
                <br />
                <br />
              </div>
            </td>
          </tr>
        </table>
      </noscript>
    </div>
  </div>
</template>
<script>
import { getKrpano, getQJInfo } from "@/api/kanban";

import { offsetToAngle } from "@/utils/krpanoJS";
import { getToken } from "@/utils/auth";

var krpano = null;
var ifSee = false;
var ifSeeTime = null;
window.getLook = function (xy) {
  let degrees = Cesium.Math.toRadians(-90);
  if (ifSee) {
    degrees = Cesium.Math.toRadians(-90);
  } else {
    degrees = Cesium.Math.toRadians(xy);
  }
  QJMark.billboard.rotation = degrees;
  EyeVisualAngle.billboard.rotation = degrees;
};

export default {
  name: "krpano",
  props: {
    // 全景id
    srcId: {
      default() {
        return "";
      },
    },
    // qj列表
    QjList: {
      default() {
        return [];
      },
    },
    // qj点位参数 index
    QJLocateParams: {
      default() {
        return {
          issues: [], // 问题
          pa_info: [], // 全景
        };
      },
    },
    // 选中的场景
    offset: {
      default() {
        return {};
      },
    },
    // 是否为任务
    ifTicket: {
      default() {
        return {};
      },
    },
  },
  components: {},
  data() {
    return {
      token: getToken(),
      ifPano: false,
      xmlhttp: null,
      xmlDoc: null,
      ifKrpano: true,

      fileHeight: 10000, // 文件高
      fileWidth: 20000, // 文件宽

      url: "",
      filesLen: "1",

      scenes: [], // 全部场景
      offsetAngle: 0, // 计算后的偏移量

      qjNameList: [],
      issNameList: [],
    };
  },
  created() {},
  mounted() {},
  methods: {
    // ! 获取url
    getKrpano(id) {
      // let id = this.src.split("?")[1].split("=")[1];
      getKrpano({ scene_id: id }).then(({ data }) => {
        if (!data) {
          this.$message.warning("未找到全景");
          return;
        }
        console.log("getKrpano", data);
        this.sectionUrl = data.section_url;
        this.filesLen = data.files_len;
        this.url = data.url;
        this.multires = data.multires;
        this.fileHeight = data.height ? data.height : 10000;
        this.fileWidth = data.width ? data.width : 20000;

        this.getQJInfo(id);

        // 判断路径
        if (data.url) {
          this.url = data.section_url + data.url;
        } else {
          if (data.files_len == 1) {
            this.url = data.section_url + "%s/l%l/%0v/l%l_%s_%0v_%0h.jpg";
          } else if (data.files_len == 0) {
            this.url = data.section_url + "%s/l%l/%v/l%l_%s_%v_%h.jpg";
          }
        }

        // 判断大小
        if (data.multires) {
          this.multires = data.multires + "";
        } else {
          if (data.files_len == 1) {
            this.multires = "512,768,1664,3200,6400";
          } else if (data.files_len == 0) {
            this.multires = "512,1024,2048,3840";
          }
        }
        this.ifKrpano = false;
        this.$nextTick(() => {
          this.ifKrpano = true;
          if (krpano) {
            krpano = null;
          }
          this.$nextTick(() => {
            ifSee = true;
            clearInterval(ifSeeTime);
            ifSeeTime = null;
            ifSeeTime = setTimeout(() => {
              ifSee = false;
            }, 4200);
            this.showKrpano();
          });
        });
      });
    },
    // 获取全景信息
    async getQJInfo(id) {
      let infoRes = await getQJInfo({
        three_d:
          "https://www.guihuao.com/2022/quanjing/1.0/index.html?scene_id=" + id,
      });
      console.log(infoRes);
      if (infoRes.error_code === 0) {
        let offset = infoRes.data.offset || 0;
        this.offsetAngle = offsetToAngle(offset, this.fileWidth);

        console.log("offset", this.offsetAngle);
      }
    },
    // ! 显示全景scene_id
    showKrpano() {
      // let settings = ;
      // settings["scene"].thumburl =
      //   "panos/4690519303701663745_stitch.tiles/thumb.jpg";
      let xml = "krpano/tour2024-3-18.xml";
      if (this.ifTicket) {
        xml = "krpano/production2024-9-21.xml";
      }

      let KrpanoData = {
        swf: "krpano/krpano.swf",
        xml: xml,
        target: "pano",
        initvars: {
          // MYURL: "panos/4690519303701663745_stitch.tiles/"
          sceneName: "XXX",
          MYURL: this.sectionUrl,
          TOKEN: this.token,
          FILESLEN: this.filesLen,
          URL: this.url,
          MULTIRES: this.multires,
          OFFSET: this.offsetAngle || 0,
        },
        html5: "auto",
        mobilescale: 1.0,
        passQueryParameters: true,
        onready: this.krpano_onready_callback, //回调函数，获取Krpano 对象
      };
      console.log("KrpanoData", KrpanoData);
      embedpano(KrpanoData);
    },
    // ? krpano回调
    krpano_onready_callback(krpano_interface) {
      krpano = krpano_interface;
      // 暂时隐藏 打点
    },
    // let h = krpano.get("view.hlookat"); // 水平视角
    // let v = krpano.get("view.vlookat"); // 垂直视角

    // ! 添加热点
    addHotsport(h, v, code, url, ifQJ, hotName) {
      let that = this;
      if (krpano) {
        let hs_name = "hs" + code; // 多次点击增加热点，每个热点的名字
        // call(action)调用并执行krpano操作代码，此处为addhotsport
        krpano.call("addhotspot(" + hs_name + ")");
        // set(variable, value)，将krpano变量设置为给定值，为hotsport设置url
        krpano.set("hotspot[" + hs_name + "].url", url);
        // 设置坐标
        krpano.set("hotspot[" + hs_name + "].ath", h);
        krpano.set("hotspot[" + hs_name + "].atv", v);
        // 设置宽高
        krpano.set("hotspot[" + hs_name + "].width", 25);
        krpano.set("hotspot[" + hs_name + "].height", 25);
        // * 设置热点是否跟随场景进行3D扭曲
        krpano.set("hotspot[" + hs_name + "].distorted", false);
        // 热点点击事件
        if (krpano.get("device.html5")) {
          // 对于HTML5，可以将JS函数直接分配给krpano事件
          if (ifQJ) {
            // 全景
            krpano.set("hotspot[" + hs_name + "].text", hotName);
            krpano.set(
              "hotspot[" + hs_name + "].onloaded",
              "add_all_the_time_tooltip()"
            );
            krpano.set(
              "hotspot[" + hs_name + "].onclick",
              function (hs) {
                that.QjList.forEach((qj) => {
                  qj.scenes.forEach((scene) => {
                    if (scene.qj.split("?scene_id=")[1] == code) {
                      that.$bus.emit("changeQj", qj);
                      that.$parent.srcId = code;
                    }
                  });
                });
                // alert("这是全景" + hs);
              }.bind(null, hs_name)
            );
          } else {
            // 问题
            krpano.set(
              "hotspot[" + hs_name + "].onclick",
              function (hs) {
                // alert('hotspot "' + hs + '" clicked');
                window.open(
                  "http://datav.flysee.com/beta/front/#/shared2?problemCode=" +
                    code +
                    "&title=" +
                    document.title,
                  "",
                  "height=1080,width=1920, scrollbars=yes,status =yes"
                );
              }.bind(null, hs_name)
            );
          }
        } else {
          // 对于Flash，需要使用js（）操作从Flash调用js（此代码适用于Flash和HTML5）
          krpano.set(
            "hotspot[" + hs_name + "].onclick",
            "js( alert(calc('hotspot \"' + name + '\" clicked')) );"
          );
        }
      }
    },

    qjChange(visible) {
      this.qjNameList.forEach((name) => {
        krpano.set("hotspot[" + name + "].visible", visible);
      });
    },
    issChange(visible) {
      this.issNameList.forEach((name) => {
        krpano.set("hotspot[" + name + "].visible", visible);
      });
    },
    // ! 删除热点
    removeHotspot() {
      if (krpano) {
        krpano.call("loop(hotspot.count GT 0, removehotspot(0) );");
      }
    },
    // ! 点击添加
    handleKrpanoClick(event) {
      if (!this.ifHeight) return;
      krpano.call("mytest");
      let toh = krpano.get("toh");
      var tov = krpano.get("tov");
      let fileWidth = this.fileWidth / 2;
      let fileHeight = this.fileHeight / 2;
      let x = +((toh / 180) * fileWidth + fileWidth).toFixed(3);
      let y = +((tov / 180) * fileHeight + fileHeight).toFixed(3);
      this.points.push([x, y]);
      this.addHotsport(toh, tov, "point" + this.pointNum);
      this.pointNum++;
      if (this.pointNum === 2) {
        this.getHeight();
        this.ifHeight = false;
      }
    },
    // ? 测高
    getHeight() {
      let params = {
        scene_id: this.scene_id,
        points: this.points, // 20000,10000 先
      };
      getHeight(params).then((res) => {
        alert(res.data);
        this.removeHotspot();
        this.ifHeight = true;
        this.pointNum = 0;
        this.points = [];
      });
    },
  },
  computed: {},
  watch: {
    srcId: {
      handler(newVal, oldVal) {
        if (!!newVal) {
          this.getKrpano(newVal);
        }
      },
      deep: true,
      immediate: true,
    },
    offset: {
      handler(newVal, oldVal) {
        // this.offsetAngle = offsetToAngle(newVal, this.fileWidth);
      },
      deep: true,
      immediate: true,
    },
  },
  beforeDestroy() {
    krpano = null;
  },
};
</script>

<style lang="scss" scoped>
.krpano {
  width: 100%;
  height: 100%;
  // background-color: skyblue;
  #pano {
    /* display: inline-block; */
    width: 100%;
    height: 100%;
    // background-color: skyblue;
  }
}
</style>
